﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MongoDB.Configuration;
using MongoDB;
using MvcDemo.Move.Models.Passport;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using MvcDemo.Move.Models.DBUtility;
using MongoDB.Bson.IO;

namespace MvcDemo.Move.Controllers
{
    public class MongoDBController : Controller
    {
        //
        // GET: /MongoDB/

        public ActionResult Index()
        {
            Test10GenMongo();

            return View();
        }

        public void Test10GenMongo()
        {
            #region

            var activeUser = MongoDBHelper.GetCollection("passport", "activeUsers");
            activeUser.Remove(Query.EQ("UserID", 38000));
            //var query = Query.EQ("_id", activeUser.FindOne()["_id"]);
            //query = Query.EQ("name", "tom");
            //var update = Update.AddToSetEachWrapped("numbers", "12", "13");
            //Response.Write(update.ToJson());
            //SafeModeResult smr = activeUser.Update(query, update, MongoDB.Driver.UpdateFlags.Multi);
            //update = Update.SetWrapped("numbers", new int[] { 11, 12 });
            return;
            #region
            var settings = new MongoServerSettings();
            settings.ConnectionMode = ConnectionMode.Direct;
            //settings.ConnectTimeout = TimeSpan.FromSeconds(1);
            //settings.DefaultCredentials = MongoCredentials.Create("username", "password");
            //settings.GuidRepresentation = GuidRepresentation.CSharpLegacy;
            //settings.IPv6 = false;
            //settings.MaxConnectionIdleTime = TimeSpan.FromSeconds(2);
            //settings.MaxConnectionLifeTime = TimeSpan.FromSeconds(3);
            //settings.MaxConnectionPoolSize = 99;
            //settings.MinConnectionPoolSize = 11;
            //settings.ReplicaSetName = "rs1";
            //settings.SafeMode = SafeMode.Create(5, TimeSpan.FromSeconds(4));
            //settings.Server = new MongoServerAddress("server");
            //settings.SlaveOk = true;
            //settings.SocketTimeout = TimeSpan.FromSeconds(5);
            //settings.WaitQueueSize = 55;
            //settings.WaitQueueTimeout = TimeSpan.FromSeconds(6);

            var servers = new[] { new MongoServerAddress("192.168.1.201", 39100), 
                new MongoServerAddress("192.168.1.203", 39100) };
            //  new MongoServerAddress("192.168.1.202", 39100), 
            settings.Servers = servers;
            #endregion

            //MongoServer server = MongoServer.Create("mongodb://192.168.1.201:39100,192.168.1.202:39100,192.168.1.203:39100");//"mongodb://192.168.1.201:39100,192.168.1.202:39100,192.168.1.203:39100"
            MongoServer server = MongoServer.Create(settings);

            //server.Connect();// 不需要打开
            MongoDB.Driver.MongoDatabase database = server["passport"];
            //database = server.GetDatabase("testABC");
            //Response.Write(server.Settings. + "  ");
            //server.CreateDatabaseSettings("passport");
            //using (database.RequestStart())
            {
                var activeUsers = database.GetCollection<ActiveUserEntity>("activeUsers");

                //for (var i = 0; i < 100; i++)
                //{
                //    activeUsers.Save<ActiveUserEntity>(new ActiveUserEntity { GuidID = Guid.NewGuid(), Ip = 127000000001, CreateDate = DateTime.Now, LastActivityDate = DateTime.Now, UserID = i * 2000, WebSiteId = 1000, IsAnonymous = false });
                //}
                //activeUsers.Insert<ActiveUserEntity>(new ActiveUserEntity { GuidID = Guid.NewGuid(), WebSiteId = 5, UserID = 100989 });
                //BsonDocument query = new BsonDocument { { "author", "Kurt Vonnegut" } };
                //var query = Query.All("", "");

                MongoCursor<ActiveUserEntity> result = activeUsers.FindAllAs<ActiveUserEntity>().SetLimit(10);

                Response.Write(result.Count());
                foreach (var item in result)
                {
                    var subItem = item;
                    //Response.Write(item.GuidID.ToString());
                }
            }
            // server.Disconnect();
            #endregion
        }

        public void GetSamusMongo()
        {
            #region
            var config = new MongoConfigurationBuilder();
            config.Mapping(mapping =>
            {
                mapping.DefaultProfile(profile =>
                {
                    profile.SubClassesAre(t => t.IsSubclassOf(typeof(MyClass)));
                });
                mapping.Map<MyClass>();
                mapping.Map<SubClass>();
            });

            config.ConnectionString("server=192.168.1.201:39100,192.168.1.202:39100,192.168.1.203:39100");
            using (Mongo mongo = new Mongo(config.BuildConfiguration()))
            {
                mongo.Connect();

                try
                {
                    var database = mongo.GetDatabase("Passport11");
                    var collection = database.GetCollection<ActiveUserEntity>();
                    var newAction = new ActiveUserEntity { GuidID = Guid.NewGuid(), Ip = 127000000001, UserID = 10086, WebSiteId = 4 };
                    collection.Save(newAction);
                    collection.FindOne(new Document("UserID", "10086"));
                    var resultList = (from item in collection.Linq()
                                      select item).ToList();
                    var qResult = collection.Linq().Where(item => (item.WebSiteId == 0)).ToList();
                }
                catch (Exception ex)
                { }

                mongo.Disconnect();
            }
            #endregion
        }
    }

    public class MyClass
    {
        public string Name { get; set; }
        public int Corners { get; set; }
    }

    public class SubClass : MyClass
    {
        public double Ratio { get; set; }
    }
}
